import { type PluginOption } from 'vite';
export const VitePluginImportDemand = (): PluginOption => {
  return {
    name: 'vite-plugin-import-demand',
    transform(code, id) {
      // console.log(id);
      let importAntdNode: Node;
      if (id.endsWith('main.tsx')) {
        const ast = this.parse(code);
        treeWalk(ast, {
          ImportDeclaration(ast) {
            // 这里的ast则必然是ImportDeclaration节点
            // 通过astExplorer可以查看ImportDeclaration的结构
            // 将antd组件库导语句: import {Button} from 'antd'
            // 转为: import Button from 'antd/es/button'
            if (ast.source.value === 'antd') {
              console.log(ast.specifiers, 'name');
              type ARRTYPE = {
                type: string;
                start: number;
                end: number;
                imported: {
                  type: string;
                  start: number;
                  end: number;
                  name: string;
                };
                local: {
                  type: string;
                  start: number;
                  end: number;
                  name: string;
                };
              }[];
              const fn = (arr: ARRTYPE) => {
                return arr
                  .map((item) => {
                    const name = item.local.name;
                    return `import ${name} from 'antd/es/${name.toLowerCase()}'`;
                  })
                  .join(';');
              };
              importAntdNode = ast;
              code =
                code.slice(0, importAntdNode.start) +
                fn(ast.specifiers) +
                code.slice(importAntdNode.end);
            }
          },
        });
      }

      return code;
    },
  };
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Node = Record<string, any>;
// 使用访问者模式遍历节点
function treeWalk(
  ast: Node | Node[],
  visitor: { [type: string]: (ast: Node) => void },
) {
  for (const node of Object.values(ast)) {
    if (node && typeof node === 'object') {
      visitor[node.type]?.(node);
      treeWalk(node, visitor);
    }
  }
}
